import { defineStore } from 'pinia'
import { ref } from 'vue'
import { IUser } from '@/api/user/type';
import { login } from '@/api/auth';
import { ILogin, } from '@/api/auth/type';
import router from '@/router';
import { resetRouter } from '@/router';
import { useStorage } from '@vueuse/core';
import { getCurrentUser } from '@/api/user';
import { getFileUrl } from '@/api/fileManage';

export const userStore = defineStore("user", () => {
  const token = useStorage("accessToken", "");
  const user = useStorage<IUser>("currentUser", {});

  const userLogin = (loginParam: ILogin) => {
    login(loginParam)
      .then(m => {
        token.value = m.data

        router.push({
          path: "sysMenuManage"
        })
        getCurrentUser().then(n => {
          user.value = n.data;
        })
      })
      .catch(error => {

      })
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      localStorage.clear();
      resetToken();
      resolve();
      resetRouter();
    })
  }

  function resetToken() {
    token.value = '';
    user.value = {};
  }

  function getAvatar(): string {
    return getFileUrl(user.value.avatar ?? "");
  }

  return { user, token, userLogin, logout, getAvatar };
}
)